/*
 *  Copyright 2008 Michael Brackx
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.googlecode.triples.resource;

import com.googlecode.triples.model.Triple;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;

@Stateless
public class TripleResourceBean implements TripleResource {

	@PersistenceContext
	private EntityManager entityManager;

	@EJB
	private TripleQueryResource tripleQueryResource;

	public TripleResourceBean() {
	}

	public TripleResourceBean(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public Response create(Triple triple) {
		entityManager.persist(triple);
		final URI uri = getUri(triple.getId());
		return Response.created(uri).build();
	}

	public Response create(String object, String attribute, String value) {
		final Triple triple = new Triple();
		triple.setObject(object);
		triple.setAttribute(attribute);
		triple.setValue(value);
		return create(triple);
	}

	public Triple read(Long id) {
		return (Triple) entityManager.createNamedQuery("tripleById").setParameter("id", id).getSingleResult();
	}

	public void update(Long id, Triple triple) {
		triple.setId(id);
		entityManager.merge(triple);
	}

	public void delete(Long id) {
		final Triple triple = read(id);
		entityManager.remove(triple);
	}

	public TripleQueryResource getTripleQueryResource() {
		return tripleQueryResource;
	}

	// private methods

	private URI getUri(Long id) {
		return UriBuilder.fromResource(TripleResource.class).path(id.toString()).build();
	}
}
